package com.zhou.springsecurityoauth2.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @author zhou
 * @version 1.0
 * @date 2022/9/30 - 09 - 30 - 14:25
 * @description com.zhou.springsecurityoauth2.utils
 */
public class JwtUtils {
    private static final String salt="35345#66546gdgvdsf";

    private static final Long  accessTimeout=1000*60*60*24L;
    private static final Long  refreshTimeout=1000*60*60*24*3L;
    public static String CreateAccessToken(String id,String object){
        JwtBuilder jwtBuilder = Jwts.builder()
                                    .setId(id)
                                    .setSubject(object)
                                    .setIssuedAt(new Date())
                                    .signWith(SignatureAlgorithm.HS256, salt)
                                    .setExpiration(new Date(System.currentTimeMillis() + accessTimeout));
        return jwtBuilder.compact();
    }

    public static String CreateRefreshToken(String id,String object){
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(object)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, salt)
                .setExpiration(new Date(System.currentTimeMillis() + refreshTimeout));
        return jwtBuilder.compact();
    }

    public static String parserToken(String token){
        Claims body = Jwts.parser().setSigningKey(salt).parseClaimsJws(token).getBody();
        return body.getSubject();

    }

    public static void main(String[] args) {
        String zhou = JwtUtils.CreateAccessToken(String.valueOf(34), "zhou");
        System.out.println(zhou);
        System.out.println(JwtUtils.parserToken(zhou));
    }
}
